package edu.lambdateacher.awt;

/*
LambdaTeacher
Copyright (C) 2000  Kim Mason
Copyright (C) 2014  Vitalij Zadneprovskij

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.apache.log4j.Logger;

public class FileOpenActionListener implements ActionListener {
	
	private static Logger log = Logger.getLogger(FileOpenActionListener.class);
	
	private AWTUserInterface parent;
	
	public FileOpenActionListener(AWTUserInterface frame){
		parent=frame;
	}
	
	public void actionPerformed(ActionEvent e) {
		String filename = null;

		FileDialog dlog = new FileDialog(parent, "Open File",
				FileDialog.LOAD);
		dlog.setDirectory(".");
		dlog.setVisible(true); // blocks until the user selects a file
								// (modal dialog)
		filename = dlog.getDirectory() + dlog.getFile();
		if (filename == null) {
			// If the user didn't pick a file, return
			return;
		}
		readFile(filename);
	}
	
	/**
	 * The readFile method takes in the name of an input file, and attemts to
	 * read that file in.
	 */
	void readFile(String infile) {
		if (infile != null) {
			try {
				FileReader finput = new FileReader(infile);

				parent.callInterpreter(finput, true);// enter the expression,
				// from a file
				// now close the file
				finput.close();

			} catch (FileNotFoundException e1) {
				log.error("Error - Invalid Input File - File Not Found.",e1);
			} catch (IOException e1) {
				log.error("Error - Could not read file - IOException occured.",e1);
			}
		} else {
			parent.error("Error - Unable to read file due to invalid filename, or no file selected.");
		}
	}
	
}
